package gerenciaDados.ciu;

import geotransform.tools.AtualizarCadastro;
import geotransform.tools.ElementoColeta;
import geotransform.tools.ElementoEDP;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JLabel;

import treinamentoClassificacao.ciu.CtrlSistema;

import java.awt.Dimension;
import java.awt.Rectangle;

public class JanAtualizarCadastroEDP extends JFrame {

	
	/**
	 * 
	 */
	File ipsFile, postesFile;
	boolean ipsOk,postesOk,outDirOk;
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	String inputIps, inputPostes, outputDir, currentPath=System.getProperty("user.dir");
	private CtrlGerenciaDados ctrlGerenciaDados = null;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					JanAtualizarCadastroEDP frame = new JanAtualizarCadastroEDP(null);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public JanAtualizarCadastroEDP(CtrlGerenciaDados controladora) {
		ctrlGerenciaDados  = controladora;
		setResizable(false);
		setTitle("Atualizar Cadastro");
		
		setBounds(100, 100, 526, 255);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		ipsOk = postesOk = outDirOk = false;
		
		
		
		final JLabel lblNomedoarquivoips = new JLabel("Nenhum arquivo selecionado");

		final JLabel lblNomedoarquivopostes = new JLabel("Nenhum arquivo selecionado");

		final JButton btnSelecionarArquivoIPs = new JButton("Selecionar Arquivo de IPs");
		btnSelecionarArquivoIPs.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser fc = new JFileChooser(currentPath);
				
			    FileNameExtensionFilter filter = new FileNameExtensionFilter("*.txt", "txt");
			    fc.setFileFilter(filter);
			    
				int returnVal = fc.showDialog(btnSelecionarArquivoIPs,"Selecionar Arquivo de IPs");
				
				if(returnVal == JFileChooser.APPROVE_OPTION) {
					File ipsFile = fc.getSelectedFile();
					inputIps = (ipsFile.getAbsolutePath());
					currentPath = (ipsFile.getAbsolutePath());
					lblNomedoarquivoips.setText(ipsFile.getName());
					
					ipsOk = true;
				}
			}
		});

		final JButton btnSelecionarArquivoPostes = new JButton("Selecionar Arquivo de Postes");
		btnSelecionarArquivoPostes.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser fc = new JFileChooser(currentPath);
				
				FileNameExtensionFilter filter = new FileNameExtensionFilter("Arquivos txt", "txt");
			    fc.setFileFilter(filter);
			    
				int returnVal = fc.showDialog(btnSelecionarArquivoPostes,"Selecionar Arquivo de Postes");

				if(returnVal == JFileChooser.APPROVE_OPTION) {
					File postesFile = fc.getSelectedFile();
					inputPostes = (postesFile.getAbsolutePath());
					currentPath = (postesFile.getAbsolutePath());
					lblNomedoarquivopostes.setText(postesFile.getName());
					
					postesOk = true;
				}
			}
		});

		final JButton btnAtualizar = new JButton("Atualizar");
		btnAtualizar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(postesOk && ipsOk){
					
					JFileChooser fc = new JFileChooser(currentPath);
					fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				
					int returnVal = fc.showDialog(btnAtualizar, "Selecionar diretorio de saida");
					if(returnVal == JFileChooser.APPROVE_OPTION) {
						File outDir = fc.getSelectedFile();
						outputDir = (outDir.getAbsolutePath());
						currentPath = (outDir.getAbsolutePath());
						
						//parte adicionada por missael
						ArrayList< ArrayList<String> > gps = ctrlGerenciaDados.getListaLocalizacoes();
						//fim - parte adicionada por missael

						AtualizarCadastro A;
						try {
							A = new AtualizarCadastro(inputIps,inputPostes,gps);
							try {
								A.match();
								
								DateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss");
								Date date = new Date();

								String outIps, outPostes, outColetas;
								String codigo = dateformat.format(date);
								outIps = outputDir + System.getProperty("file.separator") + "atualizacao-ips_" + codigo + ".txt";
								outPostes = outputDir + System.getProperty("file.separator") + "atualizacao-postes_" + codigo + ".txt";
								outColetas = outputDir + System.getProperty("file.separator") + "atualizacao-novas_" + codigo + ".txt";


								BufferedWriter ipsWriter = new BufferedWriter(new FileWriter(outIps));//
								BufferedWriter postesWriter = new BufferedWriter(new FileWriter(outPostes));//
								BufferedWriter coletasWriter = new BufferedWriter(new FileWriter(outColetas));//

								for(ElementoEDP e : A.getOutputIps()){
									ipsWriter.write(e.toString());
									ipsWriter.newLine();
								}
								ipsWriter.close();

								for(ElementoEDP e : A.getOutputPostes()){
									postesWriter.write(e.toString());
									postesWriter.newLine();
								}
								postesWriter.close();

								for(ElementoColeta e : A.getOutputColetas()){
									coletasWriter.write(e.toString());
									coletasWriter.newLine();
								}
								coletasWriter.close();
								
								JOptionPane.showMessageDialog(JanAtualizarCadastroEDP.this, "Arquivos de atualização gerados:\n\n" +  outIps + "\n" + outPostes + "\n" + outColetas + "\n");
								
								try{
									A.exportKml(outputDir);
								} catch(IOException e4){
									e4.printStackTrace();
								} catch(Exception e4){
									e4.printStackTrace();
								}
								
								dispose();
								
							} catch(IOException e3){
								JOptionPane.showMessageDialog(JanAtualizarCadastroEDP.this, "Erro ao gerar arquivo de saída.");
								e3.printStackTrace();
							}catch (Exception e3) {
								JOptionPane.showMessageDialog(JanAtualizarCadastroEDP.this, "Erro ao atualizar o cadastro.");
								e3.printStackTrace();
							}
							
						} catch (InvalidObjectException e2) {
							JOptionPane.showMessageDialog(JanAtualizarCadastroEDP.this, "Arquivo de entrada com formato inválido!");
							e2.printStackTrace();
						} catch (FileNotFoundException e2) {
							JOptionPane.showMessageDialog(JanAtualizarCadastroEDP.this, "Arquivo de entrada não encontrado.");
							e2.printStackTrace();
						} catch (IOException e2) {
							JOptionPane.showMessageDialog(JanAtualizarCadastroEDP.this, "Erro ao abrir arquivo de entrada.");
							e2.printStackTrace();
						} catch (Exception e2) {
							JOptionPane.showMessageDialog(JanAtualizarCadastroEDP.this, "Arquivo de entrada com dados inválidos.");
							e2.printStackTrace();
						}

					} else {
						System.out.println("Acao cancelada");
					}
			
				}
				else if(ipsOk){
					JOptionPane.showMessageDialog(JanAtualizarCadastroEDP.this, "É necessário selecionar o arquivo de Postes.");
				}
				else if(postesOk){
					JOptionPane.showMessageDialog(JanAtualizarCadastroEDP.this, "É necessário selecionar o arquivo de IPs.");
				}
				else{
					JOptionPane.showMessageDialog(JanAtualizarCadastroEDP.this, "É necessário selecionar o arquivo de IPs e o arquivo de Postes.");
				}
			}
		});

		final JButton btnCancelar = new JButton("Cancelar");
		btnCancelar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});

		
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(btnAtualizar)
							.addPreferredGap(ComponentPlacement.RELATED, 296, Short.MAX_VALUE)
							.addComponent(btnCancelar))
						.addComponent(btnSelecionarArquivoPostes, GroupLayout.PREFERRED_SIZE, 270, GroupLayout.PREFERRED_SIZE)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addGap(12)
							.addComponent(lblNomedoarquivopostes, GroupLayout.PREFERRED_SIZE, 258, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING, false)
							.addComponent(btnSelecionarArquivoIPs, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
							.addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
								.addGap(12)
								.addComponent(lblNomedoarquivoips, GroupLayout.PREFERRED_SIZE, 258, GroupLayout.PREFERRED_SIZE))))
					.addContainerGap())
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addComponent(btnSelecionarArquivoIPs)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(lblNomedoarquivoips)
					.addGap(18)
					.addComponent(btnSelecionarArquivoPostes)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(lblNomedoarquivopostes)
					.addGap(35)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnAtualizar)
						.addComponent(btnCancelar))
					.addContainerGap())
		);
		contentPane.setLayout(gl_contentPane);
		try {
			// faz as janelas utilizarem o renderizador do sistema atual
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			SwingUtilities.updateComponentTreeUI(this); // d� um refresh na
														// interface de todos os
														// componentes da �rvore
														// de THIS (pinta todos
														// os componentes dessa
														// janela com o novo
														// look and feel, ou
														// seja, os do sistema
														// operacional corrente)
		} catch (Exception e) { //caso ocorra algum erro, qualquer que seja
			e.printStackTrace(); //imprima no console, mas tente continuar rodando o programa (n�o coloquei pra fechar)
		}
		setLocationRelativeTo(null);
	}
}
